package org.wen.soft.generate.service;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Component;
import org.wen.soft.generate.model.GeneClass;

import javax.annotation.Resource;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Component
public class SaveService {

    @Resource
    Configuration configuration;

    /**
     * 保存Test文件
     */
    public void saveTestFile(String templateName, GeneClass model){

        try {
            Files.createDirectories(Paths.get(model.getTestFileDir()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String fileName = model.getTestFileName();
        try(FileWriter fileWriter = new FileWriter(fileName)) {
            Template template = configuration.getTemplate(templateName);
            template.process(model, fileWriter);
            System.out.println("success ---------------------------------------------- > " + fileName);
        } catch (Exception e) {
            System.out.println("error!! ---------------------------------------------- > " + fileName);
            throw new RuntimeException(e);
        }

    }
}
